import React from 'react';
import {
    Row,
    Col,
    Table,
    Button,
    Modal,
    Form,
    message,
    Switch,
    Input
} from 'antd';
import axios from 'axios';
import intercept from '../../utils/intercept';
import { config } from 'utils';
import './balance.less';

const FormItem = Form.Item;
const confirm = Modal.confirm;

class Erweima extends React.Component {
    constructor(props) {
        super(props);
        const user = JSON.parse(sessionStorage.getItem("user"));
        this.state = {
            dataSource: [],
            loading: false,
            pagination: {
                current: 1,
                pageSize: 10
            },
            onChange: this.onChange,
            keyword: '',
            visible: false,
            visibleCom: false,
            user: user,
            isEnable: true
        };
    };

    componentDidMount() {
        this.getOrderInfo();

    };

    search(value) {
        this.setState({ keyword: value });
        this.getOrderInfo({ keyword: value });
    }

    onChange = (pagination, filters, sorter) => {
        this.getOrderInfo({
            sortField: sorter.field,
            sortOrder: sorter.order,
            page: pagination.current,
            keyword: this.state.keyword,
            ...filters
        });
    };

    getOrderInfo = (params = {}) => {
        const token = sessionStorage.getItem("token");
        this.setState({ loading: true });
        var keyword = typeof (params.keyword) === "undefined"
            ? ''
            : params.keyword;
        axios
            .get(`${config.api}CustomService/GetStationContact?page=${params.page}&pageSize=${this.state.pagination.pageSize}&key=${keyword}`, { headers: { Authorization: 'Bearer ' + token } })
            .then((data) => {
                const pagination = {
                    ...this.state.pagination
                };
                pagination.total = data.data.pageList.totalRows;
                pagination.current = params.page;
                this.setState({ loading: false, dataSource: data.data.pageList.collections, pagination });
            })
            .catch(err => {
                intercept;
            })
    };

    // 编辑工作內容模态框
    showModalCompile = (e, record, status) => {
        this.setState({
            visibleCom: true
        });
        this.status = status;
        //   通过此status判断编辑还是添加
        if (status == '1') {
            this.id = record.id;
            this.props.form.setFieldsValue({
                realName: record.realName,
                phoneNum: record.phoneNum,
                stationName: record.stationName,
                position: record.position,
                describe: record.describe,
                globalCode: record.globalCode
            });
        }
    }
    handleOkCompile = (e) => {
        this.setState({
            visibleCom: false,
        });
    }
    handleCancelCompile = (e) => {
        this
            .props
            .form
            .resetFields();
        this.setState({
            visibleCom: false,
        });
    }
    CompileSubmit = (e) => {
        e.preventDefault();
        const token = sessionStorage.getItem("token");
        const params = this.props.form.getFieldsValue();
        const user = this.state.user;
        if (this.status == 1) {
            axios.post(`${config.api}CustomService/EditStationContact`,
                {
                    id: this.id, realName: params.realName, phoneNum: params.phoneNum, stationName: params.stationName,
                    position: params.position, describe: params.describe, globalCode: params.globalCode
                },
                { headers: { Authorization: 'Bearer ' + token } })
                .then((data) => {
                    // console.log(data)
                    if (data.data.result) {
                        message.success('编辑成功！')
                        this.getOrderInfo();
                        this.handleOkCompile();
                    } else {
                        message.warning(data.data.errorMessage)
                    }
                })
                .catch(err => {
                    intercept;
                })
        } else {
            axios.post(`${config.api}CustomService/AddStationContact`,
                {
                    realName: params.realName, phoneNum: params.phoneNum, stationName: params.stationName,
                    position: params.position, describe: params.describe, globalCode: params.globalCode
                },
                { headers: { Authorization: 'Bearer ' + token } })
                .then((data) => {
                    //console.log(data)
                    if (data.data.result) {
                        message.success('添加成功！')
                        this.getOrderInfo();
                        this.handleOkCompile();
                    } else {
                        message.warning(data.data.errorMessage)
                    }
                })
                .catch(err => {
                    intercept;
                })
        }

        this.setState({
            visible: false,
        });
    }
    // 编辑工作內容模态框结束~~

    // 删除
    deleteSummary = (e, text) => {
        const token = sessionStorage.getItem("token");
        let that = this;
        confirm({
            title: '确定删除吗?',
            onOk() {
                axios.post(`${config.api}CustomService/DeleteStationContact`,
                    { contactid: text.id },
                    { headers: { Authorization: 'Bearer ' + token } })
                    .then((data) => {
                        // console.log(data)
                        if (data.data.result) {
                            message.success('删除成功！')
                            that.getOrderInfo();
                            that.handleOkCompile();
                        } else {
                            message.warning(data.data.errorMessage)
                        }
                    })
                    .catch(err => {
                        intercept;
                    })
            }
        });

    }

    switchChange = (checked, userName) => {
        const token = sessionStorage.getItem("token");
        axios.post(`${config.api}User/EnableUser`, {
            userName: userName,
            isEnable: checked
        }, {
                headers: {
                    Authorization: 'Bearer ' + token
                }
            }).then((res) => {
                if (res.data.result) {
                    message.success('您已成功开启！')
                    // this.openNotification("启用禁用用户", `${checked
                    //   ? '启用'
                    //   : '禁用'}用户成功`, "#108ee9");
                } else {
                    message.warning('启用失败！' + res.data.errorMessage);
                    this.setState({ setIsEnable: false })
                    // this.openNotification("启用禁用用户", res.data.errorMessage, "red");
                }
            }).catch(err => {
                intercept;
            })
    }

    switchChangeReq = (checked) => {
        this.setState({ isEnable: checked })
    }

    render() {
        const Search = Input.Search;
        const columns = [
            {
                title: '车站名称',
                dataIndex: 'stationName',
                width: 110
            }, {
                title: '联系人',
                dataIndex: 'realName',
                width: 80

            }, {
                title: '职务',
                dataIndex: 'position',
                width: 80
            }, {
                title: '联系电话',
                width: 80,
                dataIndex: 'phoneNum'
            }, {
                title: '描述',
                dataIndex: 'describe',
                width: 150
            }, {
                title: '操作',
                width: 100,
                render: (text, record) => {
                    return (
                        <span>
                            <Button type="primary" style={{ marginRight: 5 }} ghost onClick={(e, record) => { this.showModalCompile(e, text, '1') }}>编辑</Button>
                            <Button type="danger" className="delBtn" onClick={(e, record) => { this.deleteSummary(e, text) }}>删除</Button>
                        </span>
                    )
                }
            }
        ];
        const className = "components-table-demo-nested";
        const scroll = {
            y: 600
        };
        const { getFieldDecorator } = this.props.form;
        const formItemLayout = {
            labelCol: {
                xs: {
                    span: 10
                },
                sm: {
                    span: 6
                }
            },
            wrapperCol: {
                xs: {
                    span: 10
                },
                sm: {
                    span: 14
                }
            }
        };
        return (
            <div className="orderinfo">
                {/* 編輯工作內容的模态框 */}
                <Modal
                    title="车站联系人"
                    visible={this.state.visibleCom}
                    onOk={this.handleOkCompile}
                    onCancel={this.handleCancelCompile}
                    footer={null}
                >
                    <Form onSubmit={this.CompileSubmit}>
                        <FormItem {...formItemLayout} label={(
                            <span>
                                联系人名称
                            </span>
                        )} hasFeedback>
                            {getFieldDecorator('realName', {
                                rules: [
                                    {
                                        required: true,
                                        message: 'Please input your startandend!',
                                        whitespace: true
                                    }
                                ]
                            })(<Input />)}
                        </FormItem>
                        <FormItem {...formItemLayout} label={(
                            <span>
                                联系电话
                            </span>
                        )} hasFeedback>
                            {getFieldDecorator('phoneNum', {
                                rules: [
                                    {
                                        required: true,
                                        message: 'Please input your startandend!',
                                        whitespace: true
                                    }
                                ]
                            })(<Input type="number" />)}
                        </FormItem>
                        <FormItem {...formItemLayout} label={(
                            <span>
                                车站名称
                            </span>
                        )} hasFeedback>
                            {getFieldDecorator('stationName', {
                                rules: [
                                    {
                                        required: true,
                                        message: 'Please input your startandend!',
                                        whitespace: true
                                    }
                                ]
                            })(<Input />)}
                        </FormItem>
                        <FormItem {...formItemLayout} label={(
                            <span>
                                车站编码
                            </span>
                        )} hasFeedback>
                            {getFieldDecorator('globalCode', {
                                rules: [
                                    {
                                        required: true,
                                        message: 'Please input your startandend!',
                                        whitespace: true
                                    }
                                ]
                            })(<Input />)}
                        </FormItem>
                        <FormItem {...formItemLayout} label={(
                            <span>
                                职务
                            </span>
                        )} hasFeedback>
                            {getFieldDecorator('position', {
                                rules: [
                                    {
                                        required: true,
                                        message: 'Please input your startandend!',
                                        whitespace: true
                                    }
                                ]
                            })(<Input />)}
                        </FormItem>
                        <FormItem {...formItemLayout} label={(
                            <span>
                                描述
                            </span>
                        )} hasFeedback>
                            {getFieldDecorator('describe', {
                                rules: [
                                    {
                                        required: true,
                                        message: 'Please input your startandend!',
                                        whitespace: true
                                    }
                                ]
                            })(<Input type="textarea"
                            autosize={{ minRows: 2, maxRows: 4}}
                            placeholder="请输入内容"/>)}
                        </FormItem>

                        <Row>
                            <Col span={24}>
                                <FormItem className="center">
                                    <Button type="primary" style={{ marginRight: 10 }} className="submitBtn" htmlType="submit">提交</Button>
                                    <Button onClick={this.handleCancelCompile}>取消</Button>
                                </FormItem>
                            </Col>
                        </Row>
                    </Form>
                </Modal>
                <Row gutter={8} style={{
                    marginTop: '20px'
                }}>
                    <Col span={24}>
                        <div
                            style={{
                                // textAlign: 'center',
                                margin: 10
                            }}>
                            <Search
                                placeholder="请输入任意查询条件"
                                style={{
                                    width: 600
                                }}
                                onSearch={value => this.search(value)} />

                            <Button style={{ float: 'right', width: 100 }} type="primary" onClick={() => this.showModalCompile(undefined, undefined, '0')}>添加</Button>
                        </div>
                        <Table
                            className="center"
                            {...this.state}
                            rowKey={record => record.id}
                            bordered={true}
                            className={className}
                            columns={columns}
                            scroll={scroll} />
                    </Col>
                </Row>
            </div>
        )
    }
}
const CErweima = Form.create()(Erweima);
export default CErweima
